//We will have some utility methods that are useful in random locations of our
//application and are not tied to any real business logic.  We'll keep track
//of those here.
package com.commutersconnect.util {

  //We begin with our date utilities.  At the moment, all of this is solely to
  //support more friendly messages instead of timestamps.
  object DateUtils {
    import org.joda.time.format.PeriodFormatterBuilder
    import org.joda.time.format.PeriodFormatter
    import org.joda.time.Period
    import org.joda.time.DateTime
    import java.util.Date

    private[this]
    implicit def fromJavaDate(in:Date) = new DateTime(in)

    private[this]
    val monthFormatter = new PeriodFormatterBuilder()
                      .appendMonths()
                      .appendSuffix(" month", " months")
                      .toFormatter

    private[this]
    val weekFormatter = new PeriodFormatterBuilder()
                      .appendWeeks()
                      .appendSuffix(" week", " weeks")
                      .toFormatter

    private[this]
    val dayFormatter = new PeriodFormatterBuilder()
                      .appendDays()
                      .appendSuffix(" day", " days")
                      .toFormatter

    private[this]
    val hourFormatter = new PeriodFormatterBuilder()
                      .printZeroNever()
                      .appendHours()
                      .appendSuffix(" hour", " hours")
                      .toFormatter

    //We would like to present a friendlier string to users than just a date
    //when looking at various locations that happened at a point in time.  For
    //example, if you are looking at something that happened 30 minutes ago,
    //we'll say "about thirty minutes ago" and if looking at something that
    //happened 3 days ago, we'll say "about 3 days ago".  (I am convinced I
    //could have done this same logic with a single PeriodFormatterBuilder,
    //but I didn't fully grok it at the time and this was easy enough.)
    //This is used in the ViewReport and in the Index snippets.
    def toPrettyString(from: Date, now: Date) = {
      val period = new Period(from, now)
      val retPrefix = if (period.getMonths > 0) {
        monthFormatter.print(period)
      } else if (period.getWeeks > 0) {
        weekFormatter.print(period)
      } else if (period.getDays > 0) {
        dayFormatter.print(period)
      } else if (period.getHours > 0) {
        hourFormatter.print(period)
      } else if (period.getMinutes > 30) {
        "about half an hour"
      } else if (period.getMinutes > 5) {
        "less than half an hour"
      } else {
        "minutes"
      }
      retPrefix + " ago"
    }
  }
}
